package org.footito.android.data.update;

import java.io.IOException;
import java.util.GregorianCalendar;

import org.footito.android.tools.ConvertingTools;
import org.footito.android.tools.FileLogger;
import org.footito.android.tools.Log;
import org.footito.android.ui.activity.FootitoPreferenceActity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class BroadcastForService extends BroadcastReceiver {
	private FileLogger log;

	public BroadcastForService() {
		try {
			log = new FileLogger("/footito/Broadcast");
		} catch (IOException e) {
			Log.e("IOException: " + e.getMessage());
		}
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (action != null && Intent.ACTION_BOOT_COMPLETED.equals(action)) {
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
			try {
				int value = Integer.parseInt(prefs.getString(FootitoPreferenceActity.KEY_REFRESHTIME, "0"));
				if (value > 0) {
					UpdateService.scheduleService(context, value);
				} else {
					UpdateService.unScheduleService(context);
				}
			} catch (Exception e) {
				Log.e(e);
			}

		} else {
			long time = new GregorianCalendar().getTimeInMillis();
//			log.v("Broadcast on : " + ConvertingTools.getFormattedDate(time));
			Log.v("Broadcast on : " + ConvertingTools.getFormattedDate(time));
			UpdateService.startService(context);
		}
	}

}
